package com.jolink.omiis.wechat.outer;

import java.io.IOException;
import java.io.StringReader;
import java.util.concurrent.atomic.AtomicLong;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jolink.omiis.wechat.message.IMessageHandler;
import com.jolink.omiis.wechat.util.XmlParser;

@Controller
@RequestMapping("/wechat/authority")
public class WechatAuthorityController extends AbstractWeChatController {

	private static AtomicLong authRequestCounter = new AtomicLong();

	private static Logger logger = LoggerFactory.getLogger(WechatAuthorityController.class);

	@RequestMapping(method = RequestMethod.GET)
	@Deprecated
	public void get(HttpServletRequest request, HttpServletResponse response) {
		try {
			String body = readBody(request);
			logger.info("接收到腾讯授权认证信息：{}，请求信息：{}：", request.getParameterMap(), body);
			if (!StringUtils.isEmpty(body)) {
				StringReader sr = new StringReader(body);
				Document doc = XmlParser.str2Xml(sr);
				logger.info("transfer2Xml={}。", doc.asXML());
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		String ret = "success";
		try {
			logger.info("响应服务器内容：{}。", ret);
			response.getWriter().write(ret);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
	}

	@RequestMapping(method = RequestMethod.POST)
	public void post(HttpServletRequest request, HttpServletResponse response) {
		long t1 = System.currentTimeMillis();
		logger.info("接收到腾讯授权认证请求：{}，InstanceId：{}。", request.getParameterMap(), this.hashCode());
		String requestBody = null;
		WeChatResponse wr = null;
		try {
			// setContext(context);
			requestBody = readBody(request);
			if (!StringUtils.isEmpty(requestBody)) {
				String appId = XmlParser.str2Xml(requestBody).getDocument().selectSingleNode("/xml/AppId").getText();
				if (!getContext().getCompentInfo().get("app_id").equals(appId)) {
					logger.warn("接收到授权信息，该服务平台ID：{}，接收到的ID：{}，信息不符，请确认！", getContext().getCompentInfo().get("app_id"),
							appId);
					return;
				}
				logger.info("请求内容：{}，开始处理请求信息......", requestBody);
				IMessageHandler messageHandler = null;
				try {
					messageHandler = createMessageHandler(request.getParameterMap(), requestBody);
				} catch (Exception e) {
					throw new RuntimeException("解密腾讯密文信息失败！");
				}
				messageHandler.setContext(getContext());
				wr = messageHandler.handleMessage();
				logger.info("请求信息处理完成，已请求授权次数：{}，返回处理结果：{}。", authRequestCounter.incrementAndGet(),
						wr.getResponseMessage());
			}
			response.getWriter().write(wr.getResponseMessage());
			response.getWriter().flush();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			try {
				response.getWriter().write("");
			} catch (IOException e1) {
				logger.error(e.getMessage(), e);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			try {
				response.getWriter().write("");
			} catch (IOException e1) {
				logger.error(e.getMessage(), e);
			}
		}
		long t2 = System.currentTimeMillis();
		logger.info("处理腾讯授权认证请求完成，耗时：{}毫秒。", (t2 - t1));
	}
}
